package logic

import (
	"context"
	"fmt"
	"strconv"

	"probe-users/internal/errorx"
	"probe-users/internal/svc"
	"probe-users/internal/utils"
	"probe-users/pb/users"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddPermissionToRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddPermissionToRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPermissionToRoleLogic {
	return &AddPermissionToRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 角色权限管理接口
func (l *AddPermissionToRoleLogic) AddPermissionToRole(in *users.AddPermissionToRoleRequest) (*users.AddPermissionToRoleResponse, error) {
	// 参数验证
	if err := l.validate(in); err != nil {
		return nil, err
	}

	// 解析Token
	claims, err := utils.ParseToken(in.Token, l.svcCtx.Config.JWTAuth.AccessSecret)
	if err != nil {
		return nil, err
	}

	// 检查权限：只有超级管理员可以给角色添加权限
	hasPermission, err := l.svcCtx.Enforcer.Enforce(strconv.FormatInt(claims.RoleId, 10), "role", "add_permission")
	if err != nil {
		return nil, errors.Wrapf(err, "检查权限失败")
	}
	if !hasPermission {
		return nil, errorx.ErrPermissionDenied
	}

	// 检查角色是否存在
	_, err = l.svcCtx.RoleModel.FindOne(in.RoleId)
	if err != nil {
		return nil, errors.Wrapf(err, "查询角色失败: %d", in.RoleId)
	}

	// 给角色添加权限（p, role_id, obj, act）
	roleIDStr := fmt.Sprintf("%d", in.RoleId)
	_, err = l.svcCtx.Enforcer.AddPolicy(roleIDStr, in.Obj, in.Act)
	if err != nil {
		return nil, errors.Wrapf(err, "添加权限失败: role=%d, obj=%s, act=%s", in.RoleId, in.Obj, in.Act)
	}

	// 保存策略
	if err := l.svcCtx.Enforcer.SavePolicy(); err != nil {
		return nil, errors.Wrapf(err, "保存权限策略失败")
	}

	return &users.AddPermissionToRoleResponse{
		Success: true,
	}, nil
}

func (l *AddPermissionToRoleLogic) validate(in *users.AddPermissionToRoleRequest) error {
	if in.Token == "" {
		return errorx.ErrTokenNotEmpty
	}
	if in.RoleId <= 0 {
		return errorx.ErrRoleIdInvalid
	}
	if in.Obj == "" {
		return errorx.ErrObjNotEmpty
	}
	if in.Act == "" {
		return errorx.ErrActNotEmpty
	}
	return nil
}
